package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.entity.TokenEntity;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.*;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.BusinessCardResponse;
import one.stand.service.*;
import one.stand.service.checkparam.BusinessCardServiceCheckParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * @author Administrator
 */
@Service
public class BusinessCardServiceImpl extends PublicBaseService implements BusinessCardService {

    @Autowired
    private WxMessageService wxMessageService;
    @Autowired
    private WxSunCodeService wxSunCodeService;
    @Autowired
    private CompanyAccontService companyAccontService;
    @Autowired
    BusinessCardVideoService businessCardVideoService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> createCard(BusinessCardRequest request) {
        log.info("创建名片：{}", JSON.toJSONString(request));
        if (BusinessCardServiceCheckParam.createCardCheckParam(request)) {
            return ResultModel.checkParamFail();
        }
        if (StringUtils.isBlank(request.getPersonalWx()) && StringUtils.isBlank(request.getPhone())) {
            return ResultModel.fail("请输入手机号码~!");
        }
        //查看公司状态是否正常
        CompanyModel companyModel = companyMapper.selectByPrimaryKey(request.getCompanyId());
        if (null == companyModel) {
            return ResultModel.fail("选择公司不存在~!");
        }
        if (companyModel.getIsDel().equals(BaseModel.YES_DEL)) {
            return ResultModel.fail("公司已解散~!");
        }
        if (!request.getPassword().equals(companyModel.getPassword())) {
            return ResultModel.fail("公司口令不对，请重试~!");
        }
        // 根据电话判断是否重复
        BusinessCardModel model = businessCardMapper.selectMyCard(new BusinessCardModel() {{
            setPhone(request.getPhone());
            setIsDel(0);
            setState(1);
            setCompanyId(request.getCId().intValue());
        }});
        if (model != null) {
            return ResultModel.fail("电话号码重复，无法创建~!");
        }
        // 查询公司购买服务数
        CompanyServiceModel companyServiceModel = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCompanyId());
            setType(1);
        }});
        if (companyServiceModel == null || companyServiceModel.getAvailableNum() <= 0) {
            return ResultModel.fail("可用名片数不足，请前去购买服务名片数~！");
        }

        // 修改用户头像 创建名片不再修改头像
        //UserModel userModel = userMapper.selectByPrimaryKey(request.getId().intValue());
        //if (StringUtils.isBlank(request.getLogo())) {
        //    //上传的头像为空就使用微信logo
        //    request.setLogo(userModel.getAvatarUrl());
        //} else {
        //    //不为空就将微信logo改为本次上传的logo
        //    userModel.setAvatarUrl(request.getLogo());
        //    userMapper.updateByPrimaryKeySelective(userModel);
        //}
        // 保存名片信息
        BusinessCardModel inModel = new BusinessCardModel();
        copyProperties(request, inModel);
        inModel.setUserId(request.getId().intValue());
        inModel.setCreateTime(currentDate());
        inModel.setIsDel(0);
        inModel.setState(1);
        inModel.setAuditState(AuditStateEnums.APPLY_SUCCESS.getCode());
        inModel.setCardId(null);
        if(companyModel.getUserId().equals(request.getId())){
            log.info("boss创建名片，将名片设置为boss权限");
            inModel.setRoleId(companyModel.getCompanyId());
        }else{
            log.info("普通员工创建名片");
            inModel.setRoleId(0);
        }
        businessCardMapper.insertSelective(inModel);
        log.info("进行插入名片视频操作。。。。");
        request.setMyCardId(inModel.getCardId());
        businessCardVideoService.addVideo(request);

        // 更新名片完善率情况
        updatePerfectRate(inModel.getCardId());
        // 公司购买名片服务记录表
        Integer serviceId = companyServiceModel.getServiceId();
        companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
        companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() - 1);
        companyServiceModel.setCreateTime(currentDate());
        companyServiceModel.setPurchaseType(1);
        companyServiceModel.setServiceId(null);
        companyServiceModel.setIsDel(0);
        if (companyServiceMapper.insertSelective(companyServiceModel) > 0) {
            // 修改之前的名片服务记录表为记录
            companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel() {{
                setType(0);
                setServiceId(serviceId);
            }});
        }

        // 名片太阳码
        getWxTwoCode(new BusinessCardRequest() {{
            setCardId(inModel.getCardId());
            setLoginProgramName(request.getLoginProgramName());
            setCompanyKey(request.getCompanyKey());
        }});
        // redis缓存登录信息
        Set<String> tokens = redisUtil.getKey(RedisCode.getUserLoginToken("*_"+request.getId()));
        log.info("修改缓存内容{}", JSON.toJSONString(tokens));
        for (String token : tokens) {
            if (!token.equals(RedisCode.getUserLoginToken(request.getToken()))) {
                redisUtil.remove(token);
            }
        }


        TokenEntity tokenEntity = redisUtil.get(RedisCode.getUserLoginToken(request.getToken()));
        log.info("创建名片获取当前登录token:{}",JSON.toJSONString(tokenEntity));
        if(null!=tokenEntity){
            tokenEntity.setMyCardId(inModel.getCardId());
            tokenEntity.setCId(inModel.getCompanyId().longValue());
            redisUtil.set(RedisCode.getUserLoginToken(request.getToken()), tokenEntity, redisUtil.getExpire(RedisCode.getUserLoginToken(request.getToken()), TimeUnit.SECONDS), TimeUnit.SECONDS);
        }else {
            //如果未获取到token信息 则调用删除token
            redisUtil.batchDel(RedisCode.getUserLoginToken("*"+request.getId()));
            redisUtil.remove(RedisCode.getUserLoginToken("*"+request.getId()));
        }
        //生成名片海報
        request.setCardId(model.getCardId());
        poster(request);
        return ResultModel.success(true);
    }

    @Autowired
    private PosterService posterService;

    @Override
    public void poster(BusinessCardRequest request){
        redisUtil.remove(RedisCode.getCardPoster(request.getCardId()));
        // (2) 为了建立RealData的实体，启动新的线程
        new Thread(() -> posterService.getCardPoster(request)).start();

    }

    @Override
    public ResultModel<Boolean> isCreateCompany(TokenRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CompanyModel model = companyMapper.select(new CompanyModel() {{
            setUserId(request.getId());
        }});
        if (model != null) {
            return ResultModel.success(false);
        }
        BusinessCardModel businessCardModel = businessCardMapper.select(new BusinessCardModel() {{
            setUserId(request.getId().intValue());
            setState(1);
        }});
        if (businessCardModel != null) {
            return ResultModel.success(false);
        }
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> updateCard(BusinessCardRequest request) {
        log.info("修改名片：{}", JSON.toJSONString(request));
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = businessCardMapper.selectMyCard(new BusinessCardModel() {{
            setPhone(request.getPhone());
            setMyCardId(request.getMyCardId());
            setIsDel(0);
            setState(1);
        }});

        if (model != null) {
            log.info("电话号码重复，无法修改:", model);
            return ResultModel.fail("电话号码重复，无法修改");
        }
        BusinessCardModel inModel = new BusinessCardModel();
        copyProperties(request, inModel);
        inModel.setCompanyId(null);

        //生成名片海報
        request.setCardId(request.getMyCardId());
        poster(request);

        if (businessCardMapper.updateByPrimaryKeySelective(inModel) > 0) {
            // 更新名片完善率情况
            updatePerfectRate(inModel.getCardId());
            return ResultModel.success(true);
        }
        return ResultModel.success(false);
    }

    @Override
    public ResultModel<List<BusinessCardResponse>> seeDetail(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        copyProperties(request, model);
        model.setUserId(request.getId().intValue());
        // 查询是否对默认名片有查看记录，如果没有就需要查询默认名片
        int num = seeRecordMapper.isHaveDefaultCard(new BusinessCardModel(){{
            setCompanyKey(request.getCompanyKey());
            setUserId(request.getId().intValue());
        }});
        if (num <= 0) {
            model.setType(1);
            model.setCompanyKey(request.getCompanyKey());
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<BusinessCardModel> modelList = seeRecordMapper.seeDetail(model);
        List<BusinessCardResponse> responseList = new ArrayList<>();
        modelList.forEach(m -> {
            BusinessCardResponse response = new BusinessCardResponse();
            copyProperties(m, response);
            responseList.add(response);
        });
        PageInfo<BusinessCardResponse> pageList = new PageInfo<>(responseList);
        return ResultModel.success(pageList.getList());
    }

    @Override
    public ResultModel<BusinessCardResponse> cardDetailstTst(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel outModel = businessCardMapper.select(new BusinessCardModel() {{
            setThumbsUserId(request.getId().intValue());
            setCardId(request.getCardId());
            setState(1);
        }});
        return ResultModel.success(outModel);
    }

    @Override
    public ResultModel<BusinessCardResponse> cardDetails(BusinessCardRequest request) {
        log.info("用户端名片详情参数：{}",JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardResponse response = new BusinessCardResponse();
        BusinessCardModel outModel = businessCardMapper.select(new BusinessCardModel() {{
            setThumbsUserId(request.getId().intValue());
            setCardId(request.getCardId());
            setState(1);
        }});
        if (outModel == null) {
            log.info("未获取到名片信息.....");
            return ResultModel.noData();
        }
        List<BusinessCardVideoModel> videoModel=businessCardVideoMapper.selectByCardList(new BusinessCardVideoModel(){{
            setCardId(request.getCardId());
        }});
        copyProperties(outModel, response);
        response.setVideoList(videoModel);
        response.setCardType(0);
        //验证是否是查看登录人自己的名片
        if (!outModel.getUserId().equals(request.getId().intValue())) {
            //添加查看记录
            Integer recordId = addSeeRecord(request.getId().intValue(), request.getCardId(), outModel.getCompanyId(), SeeRecordEnums.CARD.getCode(), request.getCardId());
            response.setCardType(1);
            if (!"1".equals(request.getRefresh())) {
                // 客户来访提醒微信推送提醒
                WxNoticeEntity entity = seeRecordMapper.getSendTemplateInfo(recordId);
                String[] fillData = {entity.getNickeName(), getDay(), "有人查看了您的名片，快去看看吧~！"};
                wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.CUSTOMER_ACCESS.getCode(), fillData, LoginEnum.CRM.getAccountType(), entity.getCompanyId());
            }
        }
        response.setBrowsePhoto(businessCardMapper.getBrowsePhoto(request.getCardId()));
        WebsiteModel websiteModel = websiteMapper.select(new WebsiteModel() {{
            setCompanyId(outModel.getCompanyId());
        }});
        if (null != websiteModel) {
            response.setAddress(websiteModel.getAddress());
        }
        return ResultModel.success(response);
    }

    @Override
    public ResultModel isTop(SeeRecordRequest request) {
        BusinessCardRequest businessCardRequest = new BusinessCardRequest();
        BeanUtils.copyProperties(request, businessCardRequest);
        cardDetails(businessCardRequest);
        return ResultModel.success();
    }

    @Override
    public ResultModel getUserCard(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        if (request.getUserId() != null) {
            model.setThumbsUserId(request.getUserId());
        } else {
            model.setThumbsUserId(request.getId().intValue());
        }
        model.setState(1);
        BusinessCardModel businessCardModel = businessCardMapper.select(model);
        if (businessCardModel == null) {
            return ResultModel.fail("名片不存在");
        }
        List<BusinessCardVideoModel> videoModel=businessCardVideoMapper.selectByCardList(new BusinessCardVideoModel(){{
            setCardId(businessCardModel.getCardId());
        }});
        BusinessCardResponse response = new BusinessCardResponse();
        BeanUtils.copyProperties(businessCardModel, response);
        response.setVideoList(videoModel);
        return ResultModel.success(response);
    }

    @Override
    public ResultModel delSeeCard(SeeRecordRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        SeeRecordModel model = new SeeRecordModel();
        model.setUserId(request.getId().intValue());
        model.setCardId(request.getCardId());
        r = seeRecordMapper.delSeeCard(model);
        if (r > 0) {
            return ResultModel.success("删除成功");
        }
        return ResultModel.fail("删除失败");
    }

    @Override
    public ResultModel doThumbs(SeeRecordRequest request) {
        log.info("点赞操作接口：{}",JSON.toJSONString(request));
        if (null == request || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        ThumbsModel model = new ThumbsModel();
        model.setItemId(request.getCardId());
        model.setUserId(request.getId().intValue());
        model.setItemType(1);
        List<ThumbsModel> list = thumbsMapper.select(model);
        if (list == null || list.size() <= 0) {
            model.setUserName(userMapper.selectNickeName(request.getId().toString().split(",")));
            model.setCreateTime(currentDate());
            // 增加点赞记录
            thumbsMapper.insertSelective(model);
            // 添加点赞数量
            businessCardMapper.addThumbsNum(request.getCardId());
        } else {
            // 删除点赞记录
            thumbsMapper.delete(model);
            // 减少点赞数量
            businessCardMapper.delThumbsNum(request.getCardId());
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel getWxTwoCode(BusinessCardRequest request) {
        log.info("创建太阳码传参：{}",JSON.toJSONString(request));
        if (request == null || StringUtils.isBlank(request.getCompanyKey()) || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = businessCardMapper.select(new BusinessCardModel() {{
            setCardId(request.getCardId());
            setState(1);
        }});
        if (null == model) {
            return ResultModel.noData();
        }
        if (StringUtils.isBlank(model.getWxTwoCode())) {
            CompanyAccountModel companyAccountModel = companyAccontService.selectByUserIdCopy(new CompanyAccountRequest() {{
                setCompanyKey(request.getCompanyKey());
                setAccountType(LoginEnum.USER.getAccountType());
            }});
            if (null == companyAccountModel) {
                return ResultModel.account();
            }

            String twoCode = getWxCode(request.getCardId().toString(), model.getCompanyId().toString(), companyAccountModel.getAppId(), companyAccountModel.getAppSecret());

            if (twoCode != null) {
                return ResultModel.success(twoCode);
            }
            return ResultModel.fail();
        }
        return ResultModel.success(model.getWxTwoCode());
    }

    @Override
    public ResultModel addCallsRecord(CallsPhoneRecordRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CallsPhoneRecordModel model = new CallsPhoneRecordModel();
        model.setUserId(request.getId().intValue());
        model.setCardId(request.getCardId());
        model.setCreateTime(currentDate());
        r = callsPhoneRecordMapper.insertSelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<List<BusinessCardResponse>> getUserInfo(BusinessCardRequest request) {
        if (request == null || request.getUserIds() == null || request.getUserIds().length <= 0) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserIds(request.getUserIds());
        List<BusinessCardModel> list = businessCardMapper.getUserInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<BusinessCardResponse> responseList = new ArrayList<>();
        list.forEach(m -> {
            {
                BusinessCardResponse response = new BusinessCardResponse();
                copyProperties(m, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    public String getWxCode(String cardId, String companyId, String appId, String appSecret) {
        if (StringUtils.isBlank(cardId)) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer("card=").append(cardId).append("&c=").append(companyId);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("scene", stringBuffer.toString());
        jsonObject.put("page", cardSunCode);
        String twoCode = wxSunCodeService.getWxCode(jsonObject, appId, appSecret);
        if (StringUtils.isNotBlank(twoCode)) {
            businessCardMapper.updateByPrimaryKeySelective(new BusinessCardModel() {{
                setCardId(Integer.parseInt(cardId));
                setWxTwoCode(twoCode);
            }});
            return twoCode;
        }
        return null;
    }

    /**
     * 更新名片完善率
     */
    @Async("asyncServiceExecutor")
    public void updatePerfectRate(Integer cardId){
        if(cardId == null){
            return;
        }
        BusinessCardModel model = businessCardMapper.getBusinessPerfectRate(cardId);
        if(model == null){
            return;
        }
        Integer rate = 0;
        // 姓名
        if(StringUtils.isNotBlank(model.getName())){
            rate += 10;
        }
        // 公司
        if(model.getCompanyId() != null){
            rate += 10;
        }
        // logo
        if(StringUtils.isNotBlank(model.getLogo())){
            rate += 10;
        }
        // 电话
        if(StringUtils.isNotBlank(model.getPhone())){
            rate += 10;
        }
        // 个人微信
        if(StringUtils.isNotBlank(model.getPersonalWx())){
            rate += 10;
        }
        // 公司微信
        if(StringUtils.isNotBlank(model.getCompanyWx())){
            rate += 10;
        }
        // email
        if(StringUtils.isNotBlank(model.getEmail())){
            rate += 10;
        }
        // 图片
        if(StringUtils.isNotBlank(model.getPhoto())){
            rate += 10;
        }
        // 职位
        if(StringUtils.isNotBlank(model.getPosition())){
            rate += 10;
        }
        // 录音
        if(StringUtils.isNotBlank(model.getSoundRecording())){
            rate += 5;
        }
        // 个人简介
        if(StringUtils.isNotBlank(model.getBriefIntroduction())){
            rate += 5;
        }
        model.setPerfectRate(rate);
        businessCardMapper.updatePerfectRate(model);
    }

    @Override
    public ResultModel<Boolean> switchCard(BusinessCardRequest request) {
        if(null==request.getCardId()){
            return ResultModel.checkParamFail();
        }
        BusinessCardModel outModel=businessCardMapper.selectByPrimaryKey(request.getCardId());
        if(null==outModel){
            return ResultModel.fail("名片不存在");
        }
        if(request.getRoleId().equals(request.getCId())&&!request.getRoleId().equals(outModel.getRoleId())){
            outModel.setRoleId(request.getRoleId());
            businessCardMapper.updateByPrimaryKeySelective(outModel);
            log.info("名片权限数据切换。。。");
        }

        TokenEntity tokenEntity=redisUtil.get(RedisCode.getUserLoginToken(request.getToken()));
        tokenEntity.setMyCardId(outModel.getCardId());
        tokenEntity.setCId(outModel.getCompanyId().longValue());
        tokenEntity.setRoleId(outModel.getRoleId());
        redisUtil.set(RedisCode.getUserLoginToken(request.getToken()),tokenEntity,LOGIN_TIME_LONG,TimeUnit.SECONDS);
        return ResultModel.success();
    }
}
